// 测试方法 在上一层目录中保存脚本并运行
// #!/bin/bash
// 08-get_path/a.out

//https://blog.csdn.net/weixin_38184741/article/details/85699610
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXBUFSIZE 1024

char *get_exe_path(char *buf, int count)
{
    int i;
    int rslt = readlink("/proc/self/exe", buf, count - 1);
    if (rslt < 0 || (rslt >= count - 1))
    {
        return NULL;
    }
    buf[rslt] = '\0';
    for (i = rslt; i >= 0; i--)
    {
        if (buf[i] == '/')
        {
            buf[i + 1] = '\0';
            break;
        }
    }
    return buf;
}

int main(int argc, char *argv[])
{
    char buf[MAXBUFSIZE];
    int count;
    count = readlink("/proc/self/exe", buf, MAXBUFSIZE);
    if (count < 0 || count >= MAXBUFSIZE)
    {
        printf("Failed\n");
        return (EXIT_FAILURE);
    }

    buf[count] = '\0';
    printf("/proc/self/exe -> [%s]\n", buf);

    char path[1024];
    printf("%s\n", get_exe_path(path, 1024));

    while (1)
    {
        sleep(1);
        printf("123--\n");
    }
        ;

    return (EXIT_SUCCESS);

} /* end of main */